// 游戏配对数据
const pairs = [
    ['犹太复国主义', '锡安主义'],
    ['犹太人', '以色列'],
    ['巴勒斯坦', '阿拉伯人'],
    ['巴勒斯坦分治方案', '1947年'],
    ['第一次阿以冲突', '以色列立国战争'],
    ['第二次阿以战争', '苏伊士运河战争'],
    ['第三次阿以战争', '六日战争'],
    ['阿拉法', '巴勒斯坦解放组织'],
    ['第四次阿以战争', '赎罪日战争'],
    ['阿拉伯石油输出组织', '第一次石油危机'],
    ['第五次阿以战争', '黎巴嫩战争'],
    ['以埃领袖', '《大卫营协定》'],
    ['阿以首次直接对话', '马德里会议'],
    ['以巴和平里程碑', '《奥斯陆协定》']
];

// 游戏状态
let gameState = {
    players: new Map(),
    currentPlayer: null,
    selectedCards: [],
    matchedPairs: new Set(),
    timeLeft: 300, // 5分钟
    timer: null,
    gameStarted: false,
    isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
};

// 生成二维码
function generateQRCode() {
    try {
        const qrcodeElement = document.getElementById("qrcode");
        if (!qrcodeElement) {
            console.error("找不到二维码容器元素");
            return;
        }
        
        // 清空现有二维码
        qrcodeElement.innerHTML = '';
        
        // 获取当前URL，确保使用完整的URL（包含协议）
        let currentUrl = window.location.href;
        if (!currentUrl.startsWith('http')) {
            currentUrl = 'http://' + window.location.host + window.location.pathname;
        }
        console.log('生成二维码的URL:', currentUrl);
        
        // 使用 qrcode-generator
        const typeNumber = 0; // 自动选择最小的类型
        const errorCorrectionLevel = 'L';
        const qr = qrcode(typeNumber, errorCorrectionLevel);
        qr.addData(currentUrl);
        qr.make();
        
        // 生成黑色二维码，背景为白色，增大尺寸以提高可读性
        const cellSize = 10; // 增大二维码单元格大小
        const margin = 4;
        const qrImage = qr.createImgTag(cellSize, margin);
        qrcodeElement.innerHTML = qrImage;
        
        console.log('二维码生成成功');
    } catch (error) {
        console.error("生成二维码时出错:", error);
    }
}

// 设置事件监听器
function setupEventListeners() {
    console.log('开始设置事件监听器');
    
    // 直接开始游戏按钮
    const directStartBtn = document.getElementById('direct-start-btn');
    console.log('找到开始游戏按钮:', directStartBtn);
    
    if (directStartBtn) {
        directStartBtn.addEventListener('click', function() {
            console.log('开始游戏按钮被点击');
            const rulesScreen = document.getElementById('rules-screen');
            const playerInputScreen = document.getElementById('player-input-screen');
            
            console.log('找到规则屏幕:', rulesScreen);
            console.log('找到玩家输入屏幕:', playerInputScreen);
            
            if (rulesScreen && playerInputScreen) {
                rulesScreen.style.display = 'none';
                playerInputScreen.style.display = 'block';
                console.log('成功切换屏幕');
            } else {
                console.error('找不到必要的屏幕元素');
            }
        });
        console.log('成功添加开始游戏按钮的点击事件监听器');
    } else {
        console.error('找不到开始游戏按钮');
    }

    // 开始游戏按钮
    const startGameBtn = document.getElementById('start-game-btn');
    if (startGameBtn) {
        startGameBtn.addEventListener('click', function() {
            const playerName = document.getElementById('player-name').value.trim();
            if (playerName) {
                addPlayer(playerName);
                const playerInputScreen = document.getElementById('player-input-screen');
                const gameScreen = document.getElementById('game-screen');
                
                if (playerInputScreen && gameScreen) {
                    playerInputScreen.style.display = 'none';
                    gameScreen.style.display = 'block';
                    startGame();
                }
            } else {
                alert('请输入您的姓名！');
            }
        });
    }

    // 再玩一次按钮
    const playAgainBtn = document.getElementById('play-again-btn');
    if (playAgainBtn) {
        playAgainBtn.addEventListener('click', function() {
            resetGame();
            const resultScreen = document.getElementById('result-screen');
            const rulesScreen = document.getElementById('rules-screen');
            
            if (resultScreen && rulesScreen) {
                resultScreen.style.display = 'none';
                rulesScreen.style.display = 'block';
            }
        });
    }

    // 回车键开始游戏
    const playerNameInput = document.getElementById('player-name');
    if (playerNameInput) {
        playerNameInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                startGameBtn.click();
            }
        });
    }

    // 添加触摸事件支持
    if (gameState.isMobile) {
        const gameBoard = document.getElementById('game-board');
        if (gameBoard) {
            gameBoard.addEventListener('touchstart', handleTouchStart, false);
            gameBoard.addEventListener('touchmove', handleTouchMove, false);
            gameBoard.addEventListener('touchend', handleTouchEnd, false);
        }
    }

    // 添加演示动画的配对效果
    setupDemoAnimation();
}

// 触摸事件处理
let touchStartX = 0;
let touchStartY = 0;

function handleTouchStart(e) {
    touchStartX = e.touches[0].clientX;
    touchStartY = e.touches[0].clientY;
}

function handleTouchMove(e) {
    e.preventDefault();
    const touchX = e.touches[0].clientX;
    const touchY = e.touches[0].clientY;
    
    const element = document.elementFromPoint(touchX, touchY);
    if (element && element.classList.contains('game-card')) {
        element.classList.add('selected');
    }
}

function handleTouchEnd(e) {
    const touchEndX = e.changedTouches[0].clientX;
    const touchEndY = e.changedTouches[0].clientY;
    
    const element = document.elementFromPoint(touchEndX, touchEndY);
    if (element && element.classList.contains('game-card')) {
        handleCardClick(element);
    }
}

// 重置游戏
function resetGame() {
    gameState = {
        players: new Map(),
        currentPlayer: null,
        selectedCards: [],
        matchedPairs: new Set(),
        timeLeft: 300,
        timer: null,
        gameStarted: false,
        isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    };
    
    // 清空游戏板
    const gameBoard = document.getElementById('game-board');
    gameBoard.innerHTML = '';
    
    // 清空分数显示
    document.getElementById('player-scores').innerHTML = '';
    
    // 清空最终分数
    document.getElementById('final-scores').innerHTML = '';
    
    // 清空获胜者显示
    document.querySelector('.winner-info .player-name').textContent = '';
    
    // 重置计时器显示
    document.getElementById('timer').textContent = '05:00';
}

// 初始化游戏
function initGame() {
    console.log('开始初始化游戏');
    generateQRCode(); // 生成二维码
    setupEventListeners();
    const bgm = document.getElementById('bgm');
    bgm.play().catch(error => console.log('自动播放被阻止:', error));
    console.log('游戏初始化完成');
}

// 洗牌算法
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

// 处理卡片点击
function handleCardClick(card) {
    if (!gameState.gameStarted) return;
    if (card.classList.contains('matched')) return;
    if (gameState.selectedCards.includes(card)) return;

    card.classList.add('selected');
    gameState.selectedCards.push(card);

    if (gameState.selectedCards.length === 2) {
        checkMatch();
    }
}

// 检查配对
function checkMatch() {
    const [card1, card2] = gameState.selectedCards;
    const text1 = card1.textContent;
    const text2 = card2.textContent;

    // 检查是否匹配
    const isMatch = pairs.some(pair => 
        (pair[0] === text1 && pair[1] === text2) ||
        (pair[1] === text1 && pair[0] === text2)
    );

    if (isMatch) {
        // 配对成功，立即消失
        card1.classList.add('matched');
        card2.classList.add('matched');
        gameState.matchedPairs.add(text1);
        gameState.matchedPairs.add(text2);
        
        // 更新玩家分数
        const currentPlayer = gameState.players.get(gameState.currentPlayer);
        currentPlayer.score += 1;
        updateScores();

        // 检查游戏是否结束
        if (gameState.matchedPairs.size === pairs.length * 2) {
            endGame();
        }
    } else {
        // 配对失败，快速恢复
        setTimeout(() => {
            card1.classList.remove('selected');
            card2.classList.remove('selected');
        }, 200);
    }

    gameState.selectedCards = [];
}

// 开始倒计时
function startTimer() {
    gameState.timer = setInterval(() => {
        gameState.timeLeft--;
        const minutes = Math.floor(gameState.timeLeft / 60);
        const seconds = gameState.timeLeft % 60;
        document.getElementById('timer').textContent = 
            `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

        if (gameState.timeLeft <= 0) {
            endGame();
        }
    }, 1000);
}

// 更新玩家列表显示
function updatePlayersList() {
    const playersList = document.getElementById('players-list');
    if (playersList) {
        playersList.innerHTML = '';
        gameState.players.forEach((player, name) => {
            const playerItem = document.createElement('div');
            playerItem.className = 'player-item';
            playerItem.textContent = name;
            playersList.appendChild(playerItem);
        });
    }
}

// 更新分数显示
function updateScores() {
    const scoresContainer = document.getElementById('player-scores');
    scoresContainer.innerHTML = '';
    
    // 将玩家分数转换为数组并排序
    const sortedPlayers = Array.from(gameState.players.entries())
        .sort((a, b) => b[1].score - a[1].score);
    
    sortedPlayers.forEach(([name, player], index) => {
        const scoreElement = document.createElement('div');
        scoreElement.className = 'player-score';
        scoreElement.textContent = `${index + 1}. ${name}: ${player.score}分`;
        scoresContainer.appendChild(scoreElement);
    });
}

// 结束游戏
function endGame() {
    clearInterval(gameState.timer);
    gameState.gameStarted = false;

    // 将玩家分数转换为数组并排序
    const sortedPlayers = Array.from(gameState.players.entries())
        .sort((a, b) => b[1].score - a[1].score);

    // 显示结果界面
    document.getElementById('game-screen').style.display = 'none';
    document.getElementById('result-screen').style.display = 'block';

    // 显示获胜者
    const winner = sortedPlayers[0];
    const winnerDisplay = document.querySelector('.winner-info .player-name');
    winnerDisplay.textContent = `${winner[0]} (${winner[1].score}分)`;

    // 显示最终分数和排名
    const finalScores = document.getElementById('final-scores');
    finalScores.innerHTML = '';
    
    sortedPlayers.forEach(([name, player], index) => {
        const scoreItem = document.createElement('div');
        scoreItem.className = 'score-item';
        
        const rankSpan = document.createElement('span');
        rankSpan.className = 'score-rank';
        rankSpan.textContent = `第${index + 1}名`;
        
        const nameSpan = document.createElement('span');
        nameSpan.className = 'score-name';
        nameSpan.textContent = name;
        
        const scoreSpan = document.createElement('span');
        scoreSpan.className = 'score-value';
        scoreSpan.textContent = `${player.score}分`;
        
        scoreItem.appendChild(rankSpan);
        scoreItem.appendChild(nameSpan);
        scoreItem.appendChild(scoreSpan);
        finalScores.appendChild(scoreItem);
    });
}

// 添加玩家
function addPlayer(name) {
    if (!gameState.players.has(name)) {
        gameState.players.set(name, { score: 0 });
        updateScores();
        updatePlayersList();
    }
    gameState.currentPlayer = name;
}

// 开始游戏
function startGame() {
    gameState.gameStarted = true;
    document.getElementById('rules-screen').style.display = 'none';
    document.getElementById('game-screen').style.display = 'block';
    
    // 创建游戏卡片
    const gameBoard = document.getElementById('game-board');
    gameBoard.innerHTML = ''; // 清空游戏板
    
    // 创建所有卡片数据（每个配对数据分别放在不同的方块上）
    const allCards = [];
    pairs.forEach(pair => {
        allCards.push(pair[0]); // 第一个数据
        allCards.push(pair[1]); // 第二个数据
    });
    
    // 洗牌
    shuffleArray(allCards);

    // 创建卡片元素
    allCards.forEach((text, index) => {
        const card = document.createElement('div');
        card.className = 'game-card';
        card.textContent = text;
        card.dataset.index = index;
        // 随机设置卡片颜色
        const colors = ['#4a90e2', '#e74c3c', '#2ecc71', '#f39c12', '#9b59b6', '#1abc9c'];
        card.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        card.addEventListener('click', () => handleCardClick(card));
        gameBoard.appendChild(card);
    });

    // 开始倒计时
    startTimer();
}

// 设置演示动画
function setupDemoAnimation() {
    const demoCards = document.querySelectorAll('.demo-card');
    let selectedCard = null;
    let matchedPairs = new Set();

    demoCards.forEach(card => {
        card.addEventListener('click', () => {
            if (matchedPairs.has(card.dataset.pair)) return;
            
            if (!selectedCard) {
                selectedCard = card;
                card.classList.add('selected');
            } else {
                if (selectedCard.dataset.pair === card.dataset.pair) {
                    // 配对成功
                    selectedCard.classList.add('matched');
                    card.classList.add('matched');
                    matchedPairs.add(card.dataset.pair);
                    
                    // 重置选中状态
                    selectedCard = null;
                    
                    // 检查是否所有卡片都已配对
                    if (matchedPairs.size === 1) {
                        setTimeout(() => {
                            // 重置所有卡片
                            demoCards.forEach(c => {
                                c.classList.remove('matched', 'selected');
                            });
                            matchedPairs.clear();
                        }, 1000);
                    }
                } else {
                    // 配对失败
                    setTimeout(() => {
                        selectedCard.classList.remove('selected');
                        card.classList.remove('selected');
                        selectedCard = null;
                    }, 500);
                }
            }
        });
    });
}

// 页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始初始化游戏');
    
    // 直接开始游戏按钮
    const directStartBtn = document.getElementById('direct-start-btn');
    console.log('找到开始游戏按钮:', directStartBtn);
    
    if (directStartBtn) {
        directStartBtn.addEventListener('click', function() {
            console.log('开始游戏按钮被点击');
            const rulesScreen = document.getElementById('rules-screen');
            const playerInputScreen = document.getElementById('player-input-screen');
            
            console.log('找到规则屏幕:', rulesScreen);
            console.log('找到玩家输入屏幕:', playerInputScreen);
            
            if (rulesScreen && playerInputScreen) {
                rulesScreen.style.display = 'none';
                playerInputScreen.style.display = 'block';
                console.log('成功切换屏幕');
            } else {
                console.error('找不到必要的屏幕元素');
            }
        });
        console.log('成功添加开始游戏按钮的点击事件监听器');
    } else {
        console.error('找不到开始游戏按钮');
    }
    
    // 初始化其他游戏功能
    initGame();
});

// 导出函数供外部使用
window.addPlayer = addPlayer;
window.startGame = startGame; 